/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useCallback, useRef, useMemo} from 'react';
import moment from 'moment';
import {Card, Typography, Row, Col} from 'antd';
import {querySelectOptions} from '~/service/refundReport';
import {queryR1Card2Value, queryR1Card4Value, queryR1Card5Value} from '~/service/specialClass';
import SearchForm from '../common/CommonSearchBar';
import {convertSearcherParams, formatRangePickerValue} from '../common/utils';
import FirstTwoCards from './FirstTwoCards';
import ValueCard from './ValueCard';
import RateValueCard from './RateValueCard';
import {searchFormCfg, selectUnitId, dashBoardsCfg, cardsCfg} from './config';

import './index.styl';

const {Title} = Typography;

const formItemLayout = {
    labelCol: {span: 6},
    wrapperCol: {span: 18}
};
const tailLayout = {
    wrapperCol: {span: 24}
};
// 设置默认时间
const getInitValues = () => {
    const current = new Date();
    const initValues = {
        // eslint-disable-next-line babel/camelcase
        paid_time: [moment(current).subtract(7, 'days'), moment(current)],
        // eslint-disable-next-line babel/camelcase
        teacher_nickname: '全选',
        // eslint-disable-next-line babel/camelcase
        clazz_number: '全选'
    };
    return initValues;
};

const convertDimensionValuesForPartThree = dimensionAndValues => {
    if (!Array.isArray(dimensionAndValues)) {
        return dimensionAndValues;
    }
    return dimensionAndValues?.map(item => {
        if (item?.dimensionName === 'paid_time') {
            return {
                ...item,
                dimensionName: 'refund_time',
                dimensionId: item?.dimensionId.replace(
                    'paid_time',
                    'refund_time'
                )
            };
        }
        return {...item};
    });
};

const formatDateSearchValue = formatRangePickerValue('YYYY-MM-DD HH:mm');

const GeneralViewReport = props => {
    const loadingArr = useRef([]);
    const [loading, setLoading] = useState(false);
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});

    const convertParams = params => {
        // 转换参数
        const {paid_time: paidTime, ...rest} = params || {};
        let newSearcherParams = params;
        if (paidTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedPaidTime = formatDateSearchValue(paidTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                paid_time: formattedPaidTime,
                ...rest
            };
        }
        const queryParams = convertSearcherParams(newSearcherParams);
        queryParams.forEach(item => {
            if (item.dimensionId === 'clazz_number') {
                item.dimensionName = 'cl.biz_number';
            }
        });
        return queryParams;
    };

    const [dimensionAndValues, setDimensionAndValues] = useState(
        convertParams(getInitValues())
    );

    const dimensionAndValuesForPartThree = useMemo(
        () => convertDimensionValuesForPartThree(dimensionAndValues),
        [dimensionAndValues]
    );

    /** 通过子组件loading计算按钮loading */
    const onUpdateLoading = idx => singleLoading => {
        loadingArr.current[idx] = singleLoading;
        const flag = loadingArr.current?.reduce(
            (result, item) => result || item,
            false
        );
        setLoading(flag);
    };

    /** 点击搜索按钮 */
    const handleSearch = useCallback(params => {
        setLoading(true);
        setDimensionAndValues(convertParams(params));
    }, []);

    /** 点击重置 */
    const handleReset = useCallback(() => {
        setLoading(true);
        setDimensionAndValues(convertParams(getInitValues()));
    }, []);

    // 请求单个表单配置项
    const handleFetchOptions = useCallback(
        ({
            key,
            searchKey,
            pager,
            dependItemKey,
            dependItemValue,
            isGetingMore,
            options: curOptions,
            fieldsValue
        }) => {
            let permissions = searchFormCfg.map(item => {
                if (item.key === 'paid_time') {
                    // return {
                    //     dimensionId: `${selectUnitId}_${item.key}`,
                    //     dimensionName: item.key,
                    //     filterItems: formatDateSearchValue(
                    //         fieldsValue[item.key]
                    //     )
                    // };
                    return {
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems: []
                    };
                }
                return {
                    dimensionId: `${selectUnitId}_${item.key}`,
                    dimensionName: item.key,
                    filterItems: Array.isArray(fieldsValue[item.key])
                        ? fieldsValue[item.key]
                        : fieldsValue[item.key] == null
                            ? []
                            : [fieldsValue[item.key]]
                };
            });

            permissions = permissions.filter(item => item.filterItems?.length);
            permissions.forEach(item => {
                if (item.dimensionName === 'clazz_number') {
                    item.dimensionName = 'biz_number';
                }
            });

            const params = {
                pager,
                dimensionId: `${selectUnitId}_${key}`,
                dimensionName: key === 'clazz_number' ? 'biz_number' : key,
                searchKey,
                permissions,
                unitId: selectUnitId
            };

            querySelectOptions(params).then(res => {
                const {data, pager} = res;
                let options =
                    data.map(item => ({
                        key: item,
                        value: item,
                        label: item
                    })) || [];
                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }
                setSelectOptions({key, options, pager});
            });
        },
        []
    );

    return (
        <Card className="special-class-general-view">
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                config={searchFormCfg}
                selectOptions={selectOptions}
                initialValues={getInitValues()}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
                loading={loading}
            />
            <Title level={4}>核心数据概览</Title>
            <Row wrap gutter={8}>
                <FirstTwoCards
                    defaultTitle={cardsCfg[0].defaultTitle}
                    tooltip={cardsCfg[0].tooltip}
                    dashBoard={dashBoardsCfg[0]}
                    dimensionAndValues={dimensionAndValues}
                    onUpdateLoading={onUpdateLoading(0)}
                    unitId={cardsCfg[0].unitId}
                />
                <Col key={cardsCfg[1].id} span={8}>
                    <ValueCard
                        defaultTitle={cardsCfg[1].defaultTitle}
                        tooltip={cardsCfg[1].tooltip}
                        dashBoard={dashBoardsCfg[1]}
                        dimensionAndValues={dimensionAndValues}
                        onUpdateLoading={onUpdateLoading(1)}
                        unitId={cardsCfg[1].unitId}
                        queryFunc={queryR1Card2Value}
                    />
                </Col>
                <Col key={cardsCfg[2].id} span={8}>
                    <RateValueCard
                        defaultTitle={cardsCfg[2].defaultTitle}
                        tooltip={cardsCfg[2].tooltip}
                        dashBoard={dashBoardsCfg[2]}
                        dimensionAndValues={dimensionAndValues}
                        onUpdateLoading={onUpdateLoading(2)}
                        unitId={cardsCfg[2].unitId}
                        queryFunc={queryR1Card4Value}
                    />
                </Col>
                <Col key={cardsCfg[3].id} span={8}>
                    <ValueCard
                        defaultTitle={cardsCfg[3].defaultTitle}
                        tooltip={cardsCfg[3].tooltip}
                        dashBoard={dashBoardsCfg[3]}
                        dimensionAndValues={dimensionAndValuesForPartThree}
                        onUpdateLoading={onUpdateLoading(3)}
                        unitId={cardsCfg[3].unitId}
                    />
                </Col>
                <Col key={cardsCfg[4].id} span={8}>
                    <ValueCard
                        defaultTitle={cardsCfg[4].defaultTitle}
                        tooltip={cardsCfg[4].tooltip}
                        dashBoard={dashBoardsCfg[4]}
                        dimensionAndValues={dimensionAndValues}
                        onUpdateLoading={onUpdateLoading(4)}
                        unitId={cardsCfg[4].unitId}
                        queryFunc={queryR1Card5Value}
                    />
                </Col>
            </Row>
        </Card>
    );
};

export default GeneralViewReport;
